console.clear()
console.log("~============")

var storage = chrome.storage.local;
var maodian = ""
$(function () {
    console.log("~============")
    console.log("~============~~~~")
    console.log("~============~~~~")
    console.log("~============~~~~")
    console.log("~============~~~~")
    // http://www.dht5.pw/home/book/capter/id/324460
    if (location.href.indexOf("home/book/capter/id") == -1) return;
    var title = $("title").html().trim()
    maodian = title.split("第")[0]
    storage.get(maodian, function (item) {
        console.log('item~', item);
        var _item = item;

        if (Object.keys(item).length === 0) {
            _item = {
                [maodian]: {
                    lastName: "",
                    tag: 0,
                    data: []
                }
            }
            console.log('初始化数据');
        }

        var res = _item[maodian]
        // 如果当前页面和上一次相同，则直接跳转到展示
        if (res.lastName === title) {
            openNewWindow(maodian)
        } else {
            res.data.push({
                flag: false,
                tag: $("img:eq(0)").data("original") + "?continue=null"
            })

            // 如果添加的总数大于等于5，则自动开启新的页面展示图片
            if (res.data.length - res.tag >= 5) {
                openNewWindow(maodian)
                res.tag += 5;
            }
            res.lastName = title
            storage.set({
                [maodian]: res
            }, function () {
                console.log('保存图片成功');
            })
            // 点击下一页
            NextChapterTo()
        }
    })
})

function random() {
    return Math.random().toString(16).substr(-6);
}

// 点击下一章
function NextChapterTo() {
    var aa = $('<a href="javascript:void(0);" class="afterChapter" onclick="NextChapter()"><div>下一章 &gt;</div> </a>')
    $("body").append(aa)
    aa.find("div:eq(0)").click();
    // 定时刷新，保证最后一页能重新运行上面的代码，保证了能自动打开最后的展示
    setTimeout(() => {
        location.reload();
    }, 1000 * 3);
}

$(function () {
    // "http://" + location.hostname + "#" + value + "_" + num
    if (decodeURIComponent(location.href).indexOf("#") === -1) return;
    clearBody()
    var maodian = getMaoDian()
    storage.get(maodian, function (item) {
        console.log('item===~', item);

        var total = 0;
        var res = item[maodian];
        for (let index = 0; index < res.data.length; index++) {
            const element = res.data[index];
            if (!element.flag) {
                addImg(element.tag)
                res.data[index].flag = true
                // console.log('res.data[index].flag', res.data[index].flag);
                total++
            }
            if (total >= 5) break;
        }
        storage.set({
            [maodian]: res
        }, function () {
            console.log('保存图片成功--展示');
            // console.log('res', res);
            
        })
    })
})

// 添加img元素
function addImg(src) {
    if (src.indexOf("loadimg.gif") == -1) {
        var img = $("<img src=''></img>");
        img.css("margin", "0 500px")
        img.css("width", "650px")
        // img.css("max-width", "100%")

        // http://img.dht3.pw/zimageszj2/80907/cover.jpg  
        // var src = "http://img.dht3.pw/zimageszj2/5184/109341/2.jpg"
        var da = src.split("/");
        var length = da.length;
        var dataSrc = src.substr(0, src.indexOf(da[length - 1]))

        var add = da[length - 1].split(".")[0];
        var type = da[length - 1].split(".")[1];
        for (var i = 0; i < 40; i++) {
            var p = dataSrc + add++ + "." + type;
            $(img).clone().attr("src", p).appendTo('body');
        }
    }
}


// 清空body
function clearBody() {
    $("html").attr("class", "")
    var body = $("<body></body>");
    body.css("max-width", "100%")
    body.css("width", "100%")
    body.css("max-height", "100")
    body.css("overflow", "scroll")
    body.css("text-align", "center")
    body.css("margin", "0")
    body.css("max-height", "100%")
    $("body").replaceWith(body)
}

//  得到锚点
function getMaoDian() {
    // return decodeURIComponent(location.href).split("#")[1];
    return decodeURIComponent((location.href).split("#")[1]).replace("?continue=null", '')
}

/*
 * 打开新的窗口
 * value: 锚点
 */
function openNewWindow(value) {
    window.open("http://" + location.hostname + "#" + encodeURIComponent(value));
}